/**
 * utils/taskHelpers.js
 * 提供和任务类型、积分需求相关的辅助函数。
 */

function getRequiredPoints(taskData) {
  // 可根据实际规则调整
  const basePoints = 1;
  const hasImage = (taskData.images || []).length > 0;

  // 例如有更多复杂度的任务，积分更高
  return hasImage ? basePoints + 1 : basePoints;
}

function getTaskTypeFromParameters(taskData) {
  if (taskData.topic?.includes('视频') || taskData.material_type === 'video') {
    return 'video';
  }
  if (taskData.topic?.includes('音频')) {
    return 'audio';
  }
  return 'common';
}

// 格式化任务数据用于详情显示
function formatTaskForDetail(task) {
 // 确保参数对象存在
 const parameters = task.parameters || {};
 const result=task.result || {}; // 确保result不是null
 // 统一视频URL字段
if (result.videoUrl || result.video_url) {
 const videoUrl = result.videoUrl || result.video_url;
 result.videoUrl = result.video_url = videoUrl;
}
  // 确定任务类型
  let taskType = task.taskType;

  return {
    _id: task._id,
    taskId: task.taskId,
    title: task.title || (parameters.content || task.content || '视频生成任务'),
    taskType: taskType,
    status: task.status,
    result: task.result || {}, // 确保result不是null
    parameters: parameters,
    // 兼容字段，确保详情页能获取到所有需要的数据
    topic: parameters.topic,
    content: parameters.content || task.content,
    otherContent: parameters.otherContent || '',
    speaker: parameters.speaker || task.speaker,
    emotion: parameters.emotion,
    style: parameters.style,
    images: parameters.images || [],
    material: task.material,
    createdAt: task.createdAt,
    updatedAt: task.updatedAt,
    executeId: task.executeId,
    userId: task.userId
  };
}

// 格式化任务数据用于列表显示
function formatTaskForList(task) {
  // 确保参数对象存在
  const parameters = task.parameters || {};
  const result=task.result || {}; // 确保result不是null
  // 统一视频URL字段
if (result.videoUrl || result.video_url) {
  const videoUrl = result.videoUrl || result.video_url;
  result.videoUrl = result.video_url = videoUrl;
}

  // 生成任务描述
  const content = parameters.content || task.content || '';
  const description = content.length > 8 ? content.substring(0, 8) + '...' : content;

  return {
    _id: task._id,
    taskId: task.taskId,
    title: task.title || description || '视频生成任务',
    description: description,
    taskType: task.taskType,
    status: task.status,
    result: task.result || {}, // 确保result不是null
    parameters: parameters,
    // 兼容字段
    content: parameters.content || task.content,
    speaker: parameters.speaker || task.speaker,
    material: task.material,
    createdAt: task.createdAt,
    updatedAt: task.updatedAt,
    executeId: task.executeId,
    userId: task.userId
  };
}


module.exports = {
  getRequiredPoints,
  getTaskTypeFromParameters,
  formatTaskForDetail,
  formatTaskForList
};
